//
//  JSBaseWebViewController.m
//  NiubilityProject
//
//  Created by Apple on 2018/3/8.
//  Copyright © 2018年 Apple. All rights reserved.
//

#import "JSBaseWebViewController.h"

@interface JSBaseWebViewController () <WKNavigationDelegate>
@property (nonatomic,strong) JSHandler * jsHandler;
@property (nonatomic,assign) double lastProgress;//上次进度条位置
@property (nonatomic, strong) UIBarButtonItem *backItem;
@property (nonatomic, strong) UIBarButtonItem *closeItem;
@end

@implementation JSBaseWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initWKWebView];
    self.extendedLayoutIncludesOpaqueBars = NO;
    //适配iOS11
    if (@available(iOS 11.0, *)){
        self.webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else{
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    // 设置导航按钮
    _backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage qmui_imageWithShape:QMUIImageShapeNavBack size:CGSizeMake(10, 16) tintColor:[UIColor blackColor]] style:UIBarButtonItemStylePlain
                                                                target:self
                                                                action:@selector(backButtonClicked)];
    _closeItem = [[UIBarButtonItem alloc] initWithImage:[UIImage qmui_imageWithShape:QMUIImageShapeNavClose size:CGSizeMake(12, 12) tintColor:[UIColor blackColor]]style:UIBarButtonItemStylePlain
                                                 target:self
                                                 action:@selector(closeClick)];
    
}
-(instancetype)initWithUrl:(NSString *)url naviTitle:(NSString *)titleStr{
    self = [super init];
    if (self) {
        self.url = url;
        self.title = titleStr;
        _progressViewColor = [UIColor blueColor];
    }
    return self;
}

-(instancetype)initWithHTMLStr:(NSString *)HTMLString naviTitle:(NSString *)titleStr{
    if (self = [super init]) {
        self.htmlString = HTMLString;
        self.title      = titleStr;
        _progressViewColor = [UIColor blueColor];
    }
    return self;
}
-(void)setUrl:(NSString *)url
{
    if ([_url isEqualToString: url]) {
        _url = url;
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:_url]];
        [self.webView loadRequest:request];
    }
}
- (void)setHtmlString:(NSString *)htmlString{
    if ([_htmlString isEqualToString:htmlString]) {
        _htmlString = htmlString;
        [self.webView loadHTMLString:_htmlString baseURL:nil];
    }
}

#pragma mark 初始化webview
-(void)initWKWebView
{
    WKWebViewConfiguration * configuration = [[WKWebViewConfiguration alloc]init];
    configuration.preferences.javaScriptEnabled = YES;//打开js交互
    _webConfiguration = configuration;
    _jsHandler = [[JSHandler alloc]initWithViewController:self configuration:configuration];
    
    
    self.webView = [[WKWebView alloc]initWithFrame:self.view.bounds configuration:configuration];
    _webView.navigationDelegate = self;
    _webView.backgroundColor = [UIColor clearColor];
    _webView.allowsBackForwardNavigationGestures =YES;//打开网页间的 滑动返回
    _webView.scrollView.decelerationRate = UIScrollViewDecelerationRateNormal;
    //监控进度
    [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    [self.view addSubview:_webView];
    //进度条
    _progressView = [[UIProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleDefault];
    _progressView.tintColor = _progressViewColor;
    _progressView.trackTintColor = [UIColor clearColor];
    _progressView.frame = CGRectMake(0, 0, self.view.bounds.size.width, 3.0);
    [_webView addSubview:_progressView];
    if (JSRegularIsUrl(_url)) {
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:_url]];
        [_webView loadRequest:request];
    }else if (self.htmlString.length){
        [self.webView loadHTMLString:_htmlString baseURL:nil];
    }
}
-(void)backButtonClicked
{
    if ([self.webView canGoBack]) {
        [self.webView goBack];
    }else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark --进度条
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    
    [self updateProgress:_webView.estimatedProgress];
}

#pragma mark -  更新进度条
-(void)updateProgress:(double)progress{
    self.progressView.alpha = 1;
    if(progress > _lastProgress){
        [self.progressView setProgress:self.webView.estimatedProgress animated:YES];
    }else{
        [self.progressView setProgress:self.webView.estimatedProgress];
    }
    _lastProgress = progress;
    
    if (progress >= 1) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.progressView.alpha = 0;
            [self.progressView setProgress:0];
            _lastProgress = 0;
        });
    }
}

#pragma mark --navigation delegate
//加载完毕
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    self.title = webView.title;
    [self updateProgress:webView.estimatedProgress];
    [self updateNavigationItems];
}

-(void)updateNavigationItems{
    JSLog(@"更新导航按钮--%zd",[self.webView canGoBack]);
    if ([self.webView canGoBack]) {
        self.navigationItem.leftBarButtonItems = @[self.backItem,self.closeItem];
    }else{
        self.navigationItem.leftBarButtonItems = @[self.backItem];
    }
    
}

-(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    if(webView != self.webView) {
        decisionHandler(WKNavigationActionPolicyAllow);
        return;
    }
    //更新返回按钮
    [self updateNavigationItems];
    
    NSURL * url = webView.URL;
    //打开wkwebview禁用了电话和跳转appstore 通过这个方法打开
    UIApplication *app = [UIApplication sharedApplication];
    if ([url.scheme isEqualToString:@"tel"])
    {
        if ([app canOpenURL:url])
        {
            [app openURL:url];
            decisionHandler(WKNavigationActionPolicyCancel);
            return;
        }
    }
    if ([url.absoluteString containsString:@"itunes.apple.com"])
    {
        if ([app canOpenURL:url])
        {
            [app openURL:url];
            decisionHandler(WKNavigationActionPolicyCancel);
            return;
        }
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}

-(void)backBtnClicked{
    [self.webView stopLoading];
    if ([self.webView canGoBack]) {
        [self.webView goBack];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}
-(void)closeClick{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)dealloc {
    JSLog(@"dealloc");
    [_jsHandler cancelHandler];
    self.webView.navigationDelegate = nil;
    [_webView removeObserver:self forKeyPath:@"estimatedProgress"];
}
@end


@implementation JSHandler

-(instancetype)initWithViewController:(UIViewController *)webVC configuration:(WKWebViewConfiguration *)configuration {
    self = [super init];
    if (self) {
        _webVC = webVC;
        _configuration = configuration;
        //js handler
        //注册JS 事件
        //        [configuration.userContentController addScriptMessageHandler:self name:@"showImages"];
        [configuration.userContentController addScriptMessageHandler:self name:@"backPage"];
        //        [configuration.userContentController addScriptMessageHandler:self name:@"showVideo"];
        //        [configuration.userContentController addScriptMessageHandler:self name:@"issueMoment"];
        //        [configuration.userContentController addScriptMessageHandler:self name:@"JSShare"];
        
    }
    return self;
}

#pragma mark -  JS 调用 Native  代理
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    if ([message.name isEqualToString:@"backPage"]) {
        //返回
        if (self.webVC.presentingViewController) {
            [self.webVC dismissViewControllerAnimated:YES completion:nil];
        }else{
            [self.webVC.navigationController popViewControllerAnimated:YES];
        }
    }
}

#pragma mark -  记得要移除
-(void)cancelHandler {
    //    [_configuration.userContentController removeScriptMessageHandlerForName:@"showImages"];
    [_configuration.userContentController removeScriptMessageHandlerForName:@"backPage"];
    //    [_configuration.userContentController removeScriptMessageHandlerForName:@"showVideo"];
    //    [_configuration.userContentController removeScriptMessageHandlerForName:@"issueMoment"];
    //    [_configuration.userContentController removeScriptMessageHandlerForName:@"JSShare"];
}

-(void)dealloc {
    
}

@end
